package com.howells.time.base.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.List;
import java.util.Map;

/**
 * Created by huang on 2016.10.6.
 */

public class JsonUtils {

    /**
     * 将json字符串转为实体
     *
     * @param jsonstr
     * @param cls
     * @param <T>
     * @return T
     */
    public static <T> T Json2Entity(String jsonstr, Class<T> cls) {
        T t = null;
        try {
            t = JSON.parseObject(jsonstr, cls);
        } catch (Exception e) {
            Log.e("JsonUtils", "exception" + e.getMessage());
        }
        return t;
    }

    /**
     * 将json字符串转为list
     *
     * @param jsonstr
     * @param cls
     * @param <T>
     * @return list<T>
     */
    public static <T> List<T> Json2List(String jsonstr, Class<T> cls) {
        List<T> list = null;
        try {
            list = JSON.parseArray(jsonstr, cls);
        } catch (Exception e) {
            Log.e("JsonUtils", "exception" + e.getMessage());
        }
        return list;
    }

    /**
     * 将json字符串转为Map
     *
     * @param jsonstr
     * @return map
     */
    public static Map<String, Object> Json2Map(String jsonstr) {
        Map<String, Object> map = null;
        try {
            map = JSONObject.parseObject(jsonstr);
        } catch (Exception e) {
            Log.e("JsonUtils", "exception" + e.getMessage());
        }
        return map;
    }

    /**
     * 将json字符串转为多个Map放入List中
     *
     * @param jsonstr
     * @return list<map>
     */
    public static List<Map<String, Object>> Json2List(String jsonstr) {
        List<Map<String, Object>> list = null;
        try {
            list = JSON.parseObject(jsonstr, new TypeReference<List<Map<String, Object>>>() {
            });
        } catch (Exception e) {
            Log.e("JsonUtils", "exception" + e.getMessage());
        }
        return list;
    }

    /**
     * 将对象转未json字符串
     *
     * @param o
     * @return string
     */
    public static String Object2Json(Object o) {
        String str = null;
        try {
            str = JSON.toJSONString(o);
        } catch (Exception e) {
            Log.e("JsonUtils", "exception" + e.getMessage());
        }
        return str;
    }
}
